package com.example.springboot.service.Impl;


import com.example.springboot.entity.IncorrectQuestion;
import com.example.springboot.entity.vo.IncorrectQuestionVo;
import com.example.springboot.entity.vo.MistakeStatisticsVo;
import com.example.springboot.mapper.CollectIncorrectQuestionMapper;
import com.example.springboot.mapper.IncorrectQuestionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.List;

@Service
public class IncorrectQuestionServiceImpl {

    @Autowired
    private IncorrectQuestionMapper incorrectQuestionMapper;
    @Autowired
    private CollectIncorrectQuestionMapper collectIncorrectQuestionMapper;

    public void addIncorrectQuestion(IncorrectQuestion incorrectQuestion) {
        incorrectQuestionMapper.insertIncorrectQuestion(incorrectQuestion);
    }

    public List<IncorrectQuestionVo> getIncorrectQuestionsByUserId(
            int userId, Timestamp startTime, Timestamp endTime, int page, int size) {

        // Set default time range if not provided
        if (startTime == null) {
            startTime = Timestamp.valueOf("1970-01-01 00:00:00");  // Earliest possible time
        }
        if (endTime == null) {
            endTime = new Timestamp(System.currentTimeMillis());  // Current time
        }

        // Calculate the offset for pagination
        int offset = (page - 1) * size;

        // Call the repository method to fetch the data with pagination
        List<IncorrectQuestionVo> incorrectQuestions =incorrectQuestionMapper.getIncorrectQuestionsByUserIdAndTimeRange(
                userId, startTime, endTime, offset, size);
        if (incorrectQuestions == null || incorrectQuestions.isEmpty()) {
            return incorrectQuestions;
        }
        incorrectQuestions.stream().forEach(item->{
            item.setIsCollectUser(collectIncorrectQuestionMapper.isIncorrectQuestionCollected(userId, item.getId()));
        });
        incorrectQuestions.stream()
                .filter(IncorrectQuestionVo::getIsCollectUser) // 只处理 isCollectUser 为 true 的项
                .forEach(item -> {
                    Integer collectId = collectIncorrectQuestionMapper.getCollectIdByUserIdAndIncorrectQuestionId(userId, item.getId());
                    item.setCollectId(collectId); // 假设 IncorrectQuestionVo 中有 collectId 字段
                });

        return incorrectQuestions;
    }


    public void deleteIncorrectQuestion(int id) {
        collectIncorrectQuestionMapper.deleteCollectByIncorrectQuestionId(id);
        incorrectQuestionMapper.deleteIncorrectQuestion(id);
    }

    public MistakeStatisticsVo getMistakeStatisticsVo(int userId) {
        return incorrectQuestionMapper.getTotalIncorrectQuestions(userId);
    }
}
